import { generateService } from "@umijs/openapi";

// 定义微服务配置
const services = [
  {
    name: "user",
    schemaPath: "http://localhost:9527/user/v3/api-docs",
    outputPath: "./src/api/user",
    namespace: "UserService",
    apiPrefix: "'/user'"
  },
  {
    name: "media",
    schemaPath: "http://localhost:9527/media/v3/api-docs",
    outputPath: "./src/api/media",
    namespace: "MediaService",
    apiPrefix: "'/media'"
  },
  {
    name: "mall",
    schemaPath: "http://localhost:9527/mall/v3/api-docs",
    outputPath: "./src/api/mall",
    namespace: "MallService",
    apiPrefix: "'/mall'"
  },
  {
    name: "study",
    schemaPath: "http://localhost:9527/study/v3/api-docs",
    outputPath: "./src/api/study",
    namespace: "StudyService",
    apiPrefix: "'/study'"
  },
    {
      name: "cart",
      schemaPath: "http://localhost:9527/cart/v3/api-docs",
      outputPath: "./src/api/cart",
      namespace: "CartService",
      apiPrefix: "'/cart'"
    },
    {
      name: "search",
      schemaPath: "http://localhost:9527/search/v3/api-docs",
      outputPath: "./src/api/search",
      namespace: "SearchService",
      apiPrefix: "'/search'"
    },
    {
      name: "ai",
      schemaPath: "http://localhost:9527/ai/v3/api-docs",
      outputPath: "./src/api/ai",
      namespace: "AiService",
      apiPrefix: "'/ai'"
    },


];

// 检查服务是否可访问的函数
async function checkServiceAvailability(url: string): Promise<boolean> {
  try {
    const response = await fetch(url, { 
      method: 'GET',
      headers: { 'Accept': 'application/json' },
      signal: AbortSignal.timeout(15000) // 15秒超时
    });
    return response.ok;
  } catch (error) {
    return false;
  }
}

// 为每个微服务生成API代码
async function generateAllServices() {
  console.log('🔍 检查服务可用性...');
  
  for (const service of services) {
    try {
      console.log(`\n正在为 ${service.name} 服务生成API代码...`);
      
      // 检查服务是否可访问
      const isAvailable = await checkServiceAvailability(service.schemaPath);
      if (!isAvailable) {
        console.warn(`⚠️  ${service.name} 服务不可访问: ${service.schemaPath}`);
        console.warn(`   请确保后端服务正在运行，或者跳过此服务`);
        continue;
      }
      
      console.log(`✅ ${service.name} 服务可访问，开始生成代码...`);
      
      generateService({
        requestLibPath: `import request from '@/utils/request'`,
        schemaPath: service.schemaPath,
        serversPath: service.outputPath,
        namespace: service.namespace,
        apiPrefix: service.apiPrefix,

      });
      
      console.log(`✅ ${service.name} 服务API代码生成完成`);
      console.log(`⚠️  如果生成了嵌套的api目录，请运行: npm run fix-api`);
      
    } catch (error) {
      console.error(`❌ ${service.name} 服务API代码生成失败:`, error);
      
      // 提供具体的错误解决建议
      const errorMessage = error instanceof Error ? error.message : String(error);
      
      if (errorMessage.includes('version')) {
        console.error('💡 解决方案：');
        console.error('   1. 确保Node.js >= 18.0.0');
        console.error('   2. 删除 node_modules 和 package-lock.json');
        console.error('   3. 重新运行 npm install');
      } else if (errorMessage.includes('fetch') || errorMessage.includes('network')) {
        console.error('💡 网络问题解决方案：');
        console.error('   1. 检查后端服务是否启动');
        console.error('   2. 检查端口是否正确');
        console.error('   3. 检查防火墙设置');
      } else {
        console.error('💡 通用解决方案：');
        console.error('   1. 检查API文档格式是否正确');
        console.error('   2. 确保后端服务返回有效的OpenAPI文档');
      }
    }
  }
}

// 执行生成
generateAllServices().then(() => {
  console.log('\n🎉 OpenAPI代码生成完成！');
  console.log('如果遇到问题，请运行: npm run fix-api');
}).catch((error) => {
  console.error('❌ 生成过程中发生错误:', error);
  // 使用 return 而不是 process.exit
  return;
});